package com.boot.core.exception

import com.boot.core.result.ResultEnum
import com.boot.core.result.ResultTo
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.converter.HttpMessageNotReadableException
import org.springframework.web.HttpRequestMethodNotSupportedException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException
import javax.servlet.http.HttpServletRequest

/**
 * @author rankai on 2018/3/11.
 */
@RestControllerAdvice
class GlobalExceptionHandler {

    @ExceptionHandler(Exception::class)
    fun defaultErrorHandle(req: HttpServletRequest, e: Exception): Map<String, Any> {
        return when (e) {
            is IllegalStateException -> {
                val message = e.message.toString()
                log.warn("请求:[${req.requestURI}]接口时发生错误,错误类容:$message")
                ResultTo(ResultEnum.PARAM_ERROR, "空(Null)参数")
            }
            is IllegalArgumentException -> {
                val message = e.message.toString()
                log.warn("请求:[${req.requestURI}]接口时发生错误,错误类容:$message")
                ResultTo(ResultEnum.PARAM_ERROR, "空(Null)参数:${message.split(" ")[3].replace("'", "")}")
            }
            is MethodArgumentTypeMismatchException -> {
                log.warn("请求:[${req.requestURI}]接口时发生错误,错误类容:${e.message}")
                ResultTo(ResultEnum.PARAM_ERROR, "参数类型错误")
            }
            is HttpMessageNotReadableException -> {
                log.warn("请求:[${req.requestURI}]接口时发生错误,错误类容:${e.message}")
                ResultTo(ResultEnum.PARAM_ERROR)
            }
            is HttpRequestMethodNotSupportedException -> {
                ResultTo(ResultEnum.REQUEST_METHOD_ERROR)
            }
            else -> {
                e.printStackTrace()
                log.error("请求:[${req.requestURI}]接口时发生错误,错误类容:${e.message}")
                ResultTo(ResultEnum.EXCEPTION_ERROR)
            }
        }
    }

    companion object {
        private val log: Logger = LoggerFactory.getLogger(this::class.java)
    }
}
